package com.fjrz.bbxwj.main.notice

import android.app.Activity
import android.content.Intent
import android.view.KeyEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.module.lemlin.base.BaseAbstractActivity
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.app.RZApplication
import com.fjrz.bbxwj.entity.SocketSendRequest
import com.fjrz.bbxwj.entity.SocketType
import com.fjrz.bbxwj.main.notice.adapter.ChatEmojiAdapter
import com.fjrz.bbxwj.main.notice.adapter.ChatListAdapter
import com.fjrz.bbxwj.mode.vm.MessageViewModel
import com.fjrz.bbxwj.util.HttpWebSocketUtils
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import kotlinx.android.synthetic.main.activity_message_chat.*
import kotlinx.android.synthetic.main.item_works.*

class MessageChatActivity : ViewModeActivity<MessageViewModel>() {

    companion object {

        private const val EXTRA_KEY_TITLE = "EXTRA_KEY_TITLE"

        private const val EXTRA_KEY_USER_ID = "EXTRA_KEY_USER_ID"

        fun open(activity: Activity, title: String, objectUserId: Int) {
            val intent = Intent(activity, MessageChatActivity::class.java)
            intent.putExtra(EXTRA_KEY_TITLE, title)
            intent.putExtra(EXTRA_KEY_USER_ID, objectUserId)
            activity.startActivity(intent)
        }

        private val emojis: MutableList<Int> = mutableListOf(
            0x1F601, 0x1F602, 0x1F603, 0x1F604, 0x1F605, 0x1F606, 0x1F609, 0x1F60A,
            0x1F60B, 0x1F60C, 0x1F60D, 0x1F60F, 0x1F612, 0x1F613, 0x1F614, 0x1F616,
            0x1F618, 0x1F61A, 0x1F61C, 0x1F61D, 0x1F61E, 0x1F620, 0x1F621, 0x1F622,
            0x1F623, 0x1F624, 0x1F625, 0x1F628, 0x1F629, 0x1F62A, 0x1F62B, 0x1F62D,
            0x1F630, 0x1F631, 0x1F632, 0x1F633, 0x1F635, 0x1F637, 0x1F638, 0x1F639,
            0x1F63A, 0x1F63B, 0x1F63C, 0x1F63D, 0x1F63E, 0x1F63F, 0x1F640, 0x1F645,
            0x1F646, 0x1F647, 0x1F648, 0x1F649, 0x1F64A, 0x1F64B, 0x1F64C, 0x1F64D,
            0x1F64E, 0x1F64F
        )
    }

    private val mChatListAdapter = ChatListAdapter()

    private val mChatEmojiAdapter = ChatEmojiAdapter()

    private val mTitle: String
        get() = intent?.getStringExtra(EXTRA_KEY_TITLE) ?: ""

    private val mObjectUserId: Int
        get() = intent?.getIntExtra(EXTRA_KEY_USER_ID, 0) ?: 0


    override fun viewModel(): MessageViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_message_chat

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, color = R.color.colorWhite, view = flMessageChatBar)
    }

    override fun initView() {
        ivMessageChatBack.setOnClickListener { this.finish() }

        tvMessageChatTitle.text = mTitle

        KeyboardUtils.registerSoftInputChangedListener(this as Activity) { height ->
            val layoutParams: LinearLayout.LayoutParams =
                llMessageChatBottom.layoutParams as LinearLayout.LayoutParams
            layoutParams.bottomMargin = height
            llMessageChatBottom.layoutParams = layoutParams
            rvMessageChatEmoji.visibility = View.GONE
        }

        val layoutManager = LinearLayoutManager(this)
        layoutManager.stackFromEnd = true
        rvMessageChatBody.layoutManager = layoutManager
        rvMessageChatBody.adapter = mChatListAdapter

        val layoutManager2 = GridLayoutManager(this, 7)
        layoutManager2.orientation = GridLayoutManager.VERTICAL
        rvMessageChatEmoji.layoutManager = layoutManager2
        rvMessageChatEmoji.adapter = mChatEmojiAdapter.apply {
            setNewInstance(emojis)
        }
        mChatEmojiAdapter.setOnItemClickListener { _, _, position ->
            val itemData: Int = mChatEmojiAdapter.getItem(position)
            etMessageChatContent.text.insert(
                etMessageChatContent.selectionStart,
                String(Character.toChars(itemData))
            )
        }

        ivMessageChatEmoji.setOnClickListener {
            KeyboardUtils.hideSoftInput(it)
            rvMessageChatEmoji.visibility = View.VISIBLE
        }

        ivMessageChatSend.setOnClickListener {
            if (etMessageChatContent.text.isNullOrEmpty()) {
                toast(message = "请输入消息！")
            } else {
                val token: String = RZApplication.token()
                    ?: return@setOnClickListener
                val userId: Int = RZApplication.userInfoMe()?.id
                    ?: return@setOnClickListener
                val chatSendRequest = SocketSendRequest(
                    content = etMessageChatContent.text.toString(),
                    object_user_id = mObjectUserId.toString(),
                    token = token,
                    type = SocketType.SEND.desc,
                    user_id = userId.toString()
                )
                HttpWebSocketUtils.instance()?.send(GsonUtils.toJson(chatSendRequest))
            }

        }
    }

    override fun initData() {
        viewModel.messageChatList(mObjectUserId)
    }

    override fun initViewMode() {
        viewModel.chatListLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.data?.let { chatList ->
                chatList.sortBy {
                    it.createtime
                }
                mChatListAdapter.setNewInstance(chatList)
                rvMessageChatBody.layoutManager
                    ?.scrollToPosition(mChatListAdapter.itemCount)
            }
        })
    }

    override fun onBackPressed() {
        if (rvMessageChatEmoji.visibility == View.VISIBLE) {
            rvMessageChatEmoji.visibility = View.GONE
        } else {
            super.onBackPressed()
        }
    }

    override fun onEventMainThread(any: Any) {
        if (any !is SocketType) {
            return
        }
        if (any == SocketType.SEND_FAILED) {
            toast(message = "发送失败！")
        } else if (any == SocketType.SEND_SUCCESS) {
            etMessageChatContent.text.clear()
            viewModel.messageChatList(mObjectUserId)
            rvMessageChatBody.scrollToPosition(mChatListAdapter.itemCount - 1)
        } else if (any == SocketType.RECEIVE) {
            viewModel.messageChatList(mObjectUserId)
        }
    }
}